package com.culturalCenter.dataCenter.Utils.getData;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author ISMC
 * @since 2020/9/16 12:23
 */
@Slf4j
public class UserDataUtil {

    public static String getUserBaseData(String url, int pageNum, int pageSize, String latestDate) {

        JSONObject param = new JSONObject();
        // param.out("key","value")，添加请求的参数（body）
        param.put("pageNum", pageNum);
        param.put("pageSize", pageSize);
        param.put("date", latestDate);
        StringBuilder sb = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();
            // post请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在http正文内，因此doOutput设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);
            // 设定请求的方法为"POST"，默认是GET
            conn.setRequestMethod("POST");
            // 添加请求头header
            conn.setRequestProperty("token", "token");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8))) {
                writer.write(param.toJSONString());
                writer.flush();
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
                String tmpLine;
                while ((tmpLine = reader.readLine()) != null) {
                    sb.append(tmpLine);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        conn.disconnect();
        return sb.toString();
    }

}
